<template>
	<div class="sw_system_container">
		<div class="sw_query_form" v-if="$isHasAuth(topButtons)">
			<div class="button" v-if="$isHasAuth(btnButtons)">
				<el-button size="small" type="primary" v-hasPermi="'ba9896fc77074fcead8b591273a84bf6'" icon="el-icon-plus" @click="handleOpenDialog()">新增</el-button>
				<el-button size="small" type="danger" v-hasPermi="'a6349720ebf44c8c88e4b1e26d36486d'" icon="el-icon-delete" plain @click="handleBatchDelete()">批量删除</el-button>
			</div>
			<el-form size="small" inline v-hasPermi="'14875431e22c4fefb05611b6525ce2dd'">
				<el-form-item>
					<el-input v-model="queryData.userName" clearable placeholder="用户姓名" style="width: 180px"></el-input>
				</el-form-item>
				<el-form-item>
					<el-input v-model="queryData.account" clearable placeholder="电子邮箱" style="width: 180px"></el-input>
				</el-form-item>
				<el-form-item>
					<el-select v-model="queryData.del" clearable placeholder="用户状态" style="width: 100px">
						<el-option label="正常" value="1"></el-option>
						<el-option label="封禁" value="2"></el-option>
						<el-option label="待审核" value="3"></el-option>
					</el-select>
				</el-form-item>
				<!-- <el-form-item>
					<el-select v-model="queryData.type" clearable placeholder="用户类型" style="width: 100px">
						<el-option v-for="(item, index) in dictEnums['USER_TYPE']" :key="index" :label="item.msg" :value="item.value"></el-option>
					</el-select>
				</el-form-item> -->
				<!-- <el-form-item>
					<sw-search-tree-select
						clearable
						v-model="queryData.deptId"
						:tree-data="departTree"
						:default-props="defaultProps"
						placeholder="用户院系"
						style="width: 160px"
					></sw-search-tree-select>
				</el-form-item> -->
				<el-form-item>
					<el-button type="primary" icon="el-icon-search" @click="getTabelData">查询</el-button>
				</el-form-item>
			</el-form>
		</div>
		<div class="sw_table_container">
			<el-table size="medium" ref="table" :data="tableData" stripe height="100%" @selection-change="handleSelectionChange">
				<el-table-column type="selection" width="48" align="center"></el-table-column>
				<el-table-column prop="userName" label="用户姓名" min-width="100"></el-table-column>
				<el-table-column prop="account" label="电子邮箱" min-width="200"></el-table-column>
				<!-- <el-table-column prop="type" label="用户类型" min-width="80">
					<template slot-scope="{ row }">
						<dict-tag dict="USER_TYPE" size="medium" :data="row.type"></dict-tag>
					</template>
				</el-table-column> -->
				<el-table-column prop="filed2" label="单位名称" min-width="150"></el-table-column>
				<el-table-column prop="filed4" label="单位属性" min-width="100"></el-table-column>
				<el-table-column label="状态" min-width="80">
					<template slot-scope="{ row }">
						<el-tag size="medium" type="success" v-if="row.del === '1'">正常</el-tag>
						<el-tag size="medium" type="danger" v-if="row.del === '2'">封禁</el-tag>
						<el-tag size="medium" v-if="row.del === '3'">待审核</el-tag>
					</template>
				</el-table-column>
				<el-table-column prop="createName" label="创建者" min-width="90">
					<template slot-scope="{ row }">
						{{ row.createName || '注册用户' }}
					</template>
				</el-table-column>
				<el-table-column prop="createTime" label="创建时间" min-width="160"></el-table-column>
				<el-table-column label="操作" width="150" v-if="$isHasAuth(ctrlButtons)">
					<template slot-scope="{ row }">
						<el-button type="text" @click="handleOpenDialog(row)" v-hasPermi="'e5c5760c55c14cbe93bd5b4b9b2fb6ce'">编辑</el-button>
						<el-button type="text" @click="handleDeleteData(row)" v-hasPermi="'b8973a58d6894b89ae84682994f0bb49'">删除</el-button>
						<el-dropdown size="medium" trigger="click" @command="handleUserCommand" v-if="$isHasAuth(dropButtons)">
							<el-button type="text">
								更多
								<i class="el-icon-arrow-down"></i>
							</el-button>
							<el-dropdown-menu slot="dropdown">
								<template v-if="row.del === '1'">
									<el-dropdown-item icon="sw-icon-user-banning" :command="{ type: 'blockedAccount', row }" v-hasPermi="'9bb78dfd86374296a4cd25d9f8cb0d8a'">
										封禁账号
									</el-dropdown-item>
								</template>
								<template v-if="row.del === '2'">
									<el-dropdown-item icon="sw-icon-user-deblocked" :command="{ type: 'recoverAccount', row }" v-hasPermi="'9bb78dfd86374296a4cd25d9f8cb0d8a'">
										恢复账号
									</el-dropdown-item>
								</template>
								<template v-if="row.del === '3'">
									<el-dropdown-item icon="sw-icon-user-audit" :command="{ type: 'auditAccount', row }" v-hasPermi="'89e66f5fb0414ca1b632e288848899e4'">
										审核用户
									</el-dropdown-item>
								</template>

								<el-dropdown-item icon="sw-icon-btn-passwd" :command="{ type: 'updatePassword', row }" v-hasPermi="'f06173612e61423b87b9e990db85a73a'">
									更改密码
								</el-dropdown-item>
								<el-dropdown-item icon="sw-icon-role-manage" :command="{ type: 'configRole', row }" v-hasPermi="'17e111df25d84aa4a929eaa281a2812c'">
									配置角色
								</el-dropdown-item>
							</el-dropdown-menu>
						</el-dropdown>
					</template>
				</el-table-column>
			</el-table>
		</div>
		<template v-if="dataCount > 0">
			<sw-pagination :total="dataCount" :page.sync="queryData.page" :limit.sync="queryData.limit" @change="getTabelData"></sw-pagination>
		</template>
		<config-role v-model="configDialog" :user-id="userId"></config-role>
		<user-form v-model="userDialog" :user-id="userId" :depart-data="departTree" @refresh="getTabelData"></user-form>
		<audit-user v-model="auditDialog" :user-id="userId" @refresh="getTabelData"></audit-user>
	</div>
</template>

<script>
import rsa from '@/utils/rsa';
import userForm from './form';
import auditUser from './audit';
import { mapGetters } from 'vuex';
import configRole from './configRole';
import { getDepartTree } from '@/api/system/tbSysDept';
import { getUserList, deleteUser, banAndRecoveryUser, updateUserPassword } from '@/api/system/tbSysUser';
export default {
	components: { userForm, configRole, auditUser },
	data() {
		return {
			loading: false,
			dataCount: 0,
			queryData: { page: 1, limit: 15 },
			tableData: [],
			departTree: [],
			defaultProps: { label: 'name', children: 'childList' },
			userDialog: false,
			userId: null,
			configDialog: false,
			selectedUser: [],
			auditDialog: false
		};
	},
	computed: {
		...mapGetters(['dictEnums']),
		dropButtons() {
			return ['9bb78dfd86374296a4cd25d9f8cb0d8a', '89e66f5fb0414ca1b632e288848899e4', 'f06173612e61423b87b9e990db85a73a', '17e111df25d84aa4a929eaa281a2812c'];
		},
		ctrlButtons() {
			return [...this.dropButtons, 'e5c5760c55c14cbe93bd5b4b9b2fb6ce', 'b8973a58d6894b89ae84682994f0bb49'];
		},
		btnButtons() {
			return ['ba9896fc77074fcead8b591273a84bf6', 'a6349720ebf44c8c88e4b1e26d36486d'];
		},
		topButtons() {
			return [...this.btnButtons, '14875431e22c4fefb05611b6525ce2dd'];
		}
	},
	mounted() {
		this.getTabelData();
		this.getDepartTreeData();
	},
	methods: {
		//获取部门树数据
		async getDepartTreeData() {
			let params = { del: '1', basePId: '0' };
			let result = await getDepartTree(params).then((res) => res.data);
			if (result.code === '0') {
				this.departTree = !result.data ? [] : result.data;
			}
		},

		//获取用户数据
		async getTabelData() {
			let params = { ...this.queryData };
			let result = await getUserList(params).then((res) => res.data);
			if (result.code === '0') {
				this.dataCount = parseInt(result.count);
				this.tableData = !result.data ? [] : result.data;
			}
		},

		//打开表单
		handleOpenDialog(data) {
			this.userId = !data ? null : data.id;
			this.userDialog = true;
		},

		//更多操作
		handleUserCommand(command) {
			if (command.type === 'blockedAccount') {
				this.banAndRecoveryRequest(command.row.id, 2);
			}
			if (command.type === 'recoverAccount') {
				this.banAndRecoveryRequest(command.row.id, 1);
			}
			if (command.type === 'auditAccount') {
				this.handleAuditUser(command.row.id);
			}
			if (command.type === 'updatePassword') {
				this.$bus.$emit('updatePassword', command.row.id);
			}
			if (command.type === 'configRole') {
				this.handleConfigRole(command.row.id);
			}
		},

		//封禁/恢复请求
		async banAndRecoveryRequest(id, del) {
			let messageText = '';
			let params = { id, canUpdate: 1, del };
			let result = await banAndRecoveryUser(params).then((res) => res.data);
			if (del === 1) {
				messageText = '恢复';
			} else if (del === 2) {
				messageText = '封禁';
			}
			if (result.code === '0') {
				this.getTabelData();
				this.$showCustomMessage('success', `${messageText}账号成功`);
			}
		},

		//审核用户
		handleAuditUser(id) {
			this.userId = id;
			this.auditDialog = true;
		},

		//配置角色
		handleConfigRole(id) {
			this.userId = id;
			this.configDialog = true;
		},

		//选中数据项
		handleSelectionChange(selection) {
			this.selectedUser = [...selection];
		},

		//删除数据
		handleDeleteData(row) {
			let that = this;
			that.$confirm(`此操作将删除用户<font color="#f00">【${row.userName}】</font>, 是否继续?`, '删除提示', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				dangerouslyUseHTMLString: true,
				type: 'warning',
				async beforeClose(action, instance, done) {
					if (action === 'confirm') {
						instance.confirmButtonLoading = true;
						await that.deleteDataRequest([row.id]);
						instance.confirmButtonLoading = false;
						done();
					} else {
						done();
					}
				}
			}).catch(() => {});
		},

		//批量删除数据
		handleBatchDelete() {
			let that = this;
			let nameArr = (() => {
				let text = '';
				this.selectedUser.forEach((item) => {
					text += `<font color="#f00" style="white-space: nowrap;">【${item.userName}】</font>`;
				});
				return text;
			})();
			let idArr = this.selectedUser.map((item) => item.id);
			if (idArr.length === 0) {
				this.$showCustomMessage('warning', `请先选择需要删除的数据`);
				return false;
			}
			that.$confirm(`此操作将批量删除用户：${nameArr} 是否继续?`, '删除提示', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				dangerouslyUseHTMLString: true,
				type: 'warning',
				async beforeClose(action, instance, done) {
					if (action === 'confirm') {
						instance.confirmButtonLoading = true;
						await that.deleteDataRequest(idArr);
						instance.confirmButtonLoading = false;
						done();
					} else {
						done();
					}
				}
			}).catch(() => {});
		},

		//删除数据请求
		async deleteDataRequest(params) {
			let result = await deleteUser(params).then((res) => res.data);
			if (result.code === '0') {
				this.getTabelData();
				this.$showCustomMessage('success', `删除用户成功`);
			}
		}
	}
};
</script>

<style lang="scss" scoped>
.sw_system_container {
	display: flex;
	flex-direction: column;
	padding: 16px;
}
</style>
